package com.ddd.core.filter;

import cn.hutool.core.util.StrUtil;
import com.ddd.core.wapper.XssRequestWrapper;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: zhongwenbin
 * @Date: 2023/6/25 17:54
 * @Description: 缓存包装器过滤器
 **/
public class XssContentCacheFilter implements Filter {

    private final List<String> excludes = new ArrayList<>();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 可重复读request
        ContentCachingRequestWrapper contentCachingRequestWrapper = new ContentCachingRequestWrapper((HttpServletRequest) servletRequest);
        // 可重复读response
        ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper((HttpServletResponse) servletResponse);
        // xss 过滤包装器
        XssRequestWrapper xssRequestWrapper = new XssRequestWrapper((HttpServletRequest) contentCachingRequestWrapper, excludes);
        filterChain.doFilter(xssRequestWrapper, responseWrapper);
        // 刷入response
        responseWrapper.copyBodyToResponse();
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
        String excludesStr = filterConfig.getInitParameter("excludes");
        if (StrUtil.isNotBlank(excludesStr)) {
            excludes.addAll(Arrays.asList(excludesStr.split(",")));
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
